package com.EAsystem.controller.teacher;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.Announcement;
import com.EAsystem.entity.Course;
import com.EAsystem.entity.CourseSchedule;
import com.EAsystem.entity.CourseSelection;
import com.EAsystem.entity.Grade;
import com.EAsystem.entity.Homework;
import com.EAsystem.entity.HomeworkSubmission;
import com.EAsystem.entity.Student;
import com.EAsystem.entity.Teacher;
import com.EAsystem.entity.User;
import com.EAsystem.entity.Attendance;
import com.EAsystem.entity.Leave;
import com.EAsystem.entity.Evaluation;
import com.EAsystem.mapper.CourseScheduleMapper;
import com.EAsystem.service.AnnouncementService;
import com.EAsystem.service.CourseSelectionService;
import com.EAsystem.service.CourseService;
import com.EAsystem.service.GradeService;
import com.EAsystem.service.StudentService;
import com.EAsystem.service.TeacherService;
import com.EAsystem.service.HomeworkService;
import com.EAsystem.service.HomeworkSubmissionService;
import com.EAsystem.service.AttendanceService;
import com.EAsystem.service.LeaveService;
import com.EAsystem.service.EvaluationService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.MissingServletRequestParameterException;

import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpServletRequest;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

@Controller
@RequestMapping("/teacher")
@RequireRole({2}) // 只有老师可以访问
public class TeacherController {

    @Autowired
    private AnnouncementService announcementService;
    
    @Autowired
    private CourseService courseService;
    
    @Autowired
    private TeacherService teacherService;
    
    @Autowired
    private CourseScheduleMapper courseScheduleMapper;

    @Autowired
    private CourseSelectionService courseSelectionService;

    @Autowired
    private GradeService gradeService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private HomeworkService homeworkService;

    @Autowired
    private HomeworkSubmissionService homeworkSubmissionService;

    @Autowired
    private AttendanceService attendanceService;

    @Autowired
    private LeaveService leaveService;

    @Autowired
    private EvaluationService evaluationService;

    /**
     * 作业请求DTO
     */
    public static class HomeworkRequest {
        private String courseId;
        private String title;
        private String content;
        private String deadline;

        public String getCourseId() { return courseId; }
        public void setCourseId(String courseId) { this.courseId = courseId; }
        
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        
        public String getDeadline() { return deadline; }
        public void setDeadline(String deadline) { this.deadline = deadline; }
    }

    /**
     * 作业更新请求DTO
     */
    public static class HomeworkUpdateRequest {
        private String id;
        private String title;
        private String content;
        private String deadline;

        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        
        public String getDeadline() { return deadline; }
        public void setDeadline(String deadline) { this.deadline = deadline; }
    }

    /**
     * 处理参数缺失异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public Map<String, Object> handleMissingParams(MissingServletRequestParameterException ex) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", "缺少必需参数: " + ex.getParameterName());

        return response;
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String, Object> handleException(Exception ex, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", "操作失败: " + ex.getMessage());
        
        ex.printStackTrace();
        
        return response;
    }

    @GetMapping("/home")
    public String teacherHome(Model model) {
        // 获取教务通知
        List<Announcement> academicNotifications = announcementService.findByTypeOne();
        // 获取考试安排
        List<Announcement> examNotifications = announcementService.findByTypeTwo();

        if (academicNotifications == null) {
            academicNotifications = new ArrayList<>();
        }
        if (examNotifications == null) {
            examNotifications = new ArrayList<>();
        }

        model.addAttribute("academicNotifications", academicNotifications);
        model.addAttribute("examNotifications", examNotifications);

        return "teacher/home";
    }

    @GetMapping("/notifications/academic")
    public String listAcademicNotifications(@RequestParam(defaultValue = "1") int page,
                                            @RequestParam(defaultValue = "5") int size,
                                            Model model,
                                            @RequestParam(required = false) String titleSearch) {

        PageInfo<Announcement> pageInfo;
        if (titleSearch != null && !titleSearch.isEmpty()) {
            Announcement announcement = new Announcement();
            announcement.setTitle(titleSearch);
            announcement.setType(1); // 教务通知类型
            pageInfo = announcementService.findByConditionPage(announcement, page, size);
        } else {
            pageInfo = announcementService.findByTypeOneWithPage(page, size);
        }

        if (pageInfo == null) {
            pageInfo = new PageInfo<>();
        }

        model.addAttribute("announcements", pageInfo.getList());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("titleSearch", titleSearch);

        return "teacher/academic_notifications";
    }

    @GetMapping("/notifications/exam")
    public String listExamNotifications(@RequestParam(defaultValue = "1") int page,
                                        @RequestParam(defaultValue = "5") int size,
                                        Model model,
                                        @RequestParam(required = false) String titleSearch) {

        PageInfo<Announcement> pageInfo;
        if (titleSearch != null && !titleSearch.isEmpty()) {
            Announcement announcement = new Announcement();
            announcement.setTitle(titleSearch);
            announcement.setType(2); // 考试安排类型
            pageInfo = announcementService.findByConditionPage(announcement, page, size);
        } else {
            pageInfo = announcementService.findByTypeTwoWithPage(page, size);
        }

        if (pageInfo == null) {
            pageInfo = new PageInfo<>();
        }

        model.addAttribute("announcements", pageInfo.getList());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("titleSearch", titleSearch);

        return "teacher/exam_notifications";
    }

    @GetMapping("/notifications/classroom")
    public String listClassroomNotifications(@RequestParam(defaultValue = "1") int page,
                                             @RequestParam(defaultValue = "5") int size,
                                             Model model,
                                             @RequestParam(required = false) String titleSearch) {

        PageInfo<Announcement> pageInfo;
        if (titleSearch != null && !titleSearch.isEmpty()) {
            Announcement announcement = new Announcement();
            announcement.setTitle(titleSearch);
            announcement.setType(3); // 教室安排类型
            pageInfo = announcementService.findByConditionPage(announcement, page, size);
        } else {
            pageInfo = announcementService.findByTypeThreeWithPage(page, size);
        }

        if (pageInfo == null) {
            pageInfo = new PageInfo<>();
        }

        model.addAttribute("announcements", pageInfo.getList());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("titleSearch", titleSearch);

        return "teacher/classroom_notifications";
    }

    /**
     * 我的课程页面 - 显示当前登录老师的课程
     */
    @GetMapping("/courses")
    public String listMyCourses(@RequestParam(defaultValue = "1") int page,
                               @RequestParam(defaultValue = "5") int size,
                               Model model,
                               @RequestParam(required = false) String courseSearch,
                               HttpSession session) {
        
        // 获取当前登录的老师信息
        User currentUser = (User) session.getAttribute("loggedInUser");
        if (currentUser == null) {
            return "redirect:/user/login";
        }
        
        // 通过用户ID获取教师信息
        Teacher currentTeacher = null;
        if (currentUser.getRole() == 2) { // 老师角色
            try {
                currentTeacher = teacherService.findByUserId(currentUser.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if (currentTeacher == null) {
            model.addAttribute("courses", new ArrayList<>());
            model.addAttribute("error", "无法获取教师信息，请联系管理员");
            return "teacher/courses";
        }
        
        PageInfo<Course> pageInfo = new PageInfo<>();
        try {
            if (courseSearch != null && !courseSearch.trim().isEmpty()) {
                // 搜索功能 - 只搜索当前老师的课程
                Course searchCourse = new Course();
                searchCourse.setName(courseSearch.trim());
                searchCourse.setTeacher(currentTeacher);
                pageInfo = courseService.findByConditionPageInfo(searchCourse, page, size);
            } else {
                // 获取当前老师的所有课程
                Course teacherCourse = new Course();
                teacherCourse.setTeacher(currentTeacher);
                pageInfo = courseService.findByConditionPageInfo(teacherCourse, page, size);
            }
        } catch (Exception e) {
            e.printStackTrace();
            pageInfo = new PageInfo<>();
        }

        if (pageInfo == null) {
            pageInfo = new PageInfo<>();
        }

        model.addAttribute("courses", pageInfo.getList());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("courseSearch", courseSearch);
        model.addAttribute("currentTeacher", currentTeacher);

        return "teacher/courses";
    }
    
    /**
     * 新增课程
     */
    @PostMapping("/courses/add")
    public String addCourse(Course course, 
                           @RequestParam(value = "weekdays[]", required = false) int[] weekdays,
                           @RequestParam(value = "periods[]", required = false) int[] periods,
                           @RequestParam(value = "classrooms[]", required = false) String[] classrooms,
                           HttpSession session) {
        try {
            
            
            // 获取当前登录的老师信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null || currentUser.getRole() != 2) {
                return "redirect:/user/login";
            }
            
            // 通过用户ID获取教师信息
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                return "redirect:/teacher/courses?error=teacher_not_found";
            }
            
            // 设置当前老师为课程老师
            course.setTeacher(currentTeacher);
            
            // 设置课程状态，默认为1（启用）
            course.setStatus(1);
            
            // 保存课程基本信息
            courseService.save(course);
            
            // 处理时间安排数据
            if (weekdays != null && periods != null && classrooms != null) {
                int minLength = Math.min(Math.min(weekdays.length, periods.length), classrooms.length);
                
                for (int i = 0; i < minLength; i++) {
                    // 跳过空的时间安排
                    if (weekdays[i] == 0 || periods[i] == 0) {
                        continue;
                    }
                    
                    CourseSchedule schedule = new CourseSchedule();
                    schedule.setCourse(course);  // 设置Course对象
                    schedule.setWeekday(weekdays[i]);
                    schedule.setPeriod(periods[i]);
                    schedule.setClassroom(classrooms[i] != null && !classrooms[i].trim().isEmpty() ? classrooms[i].trim() : null);
                    
                    // 保存时间安排
                    courseScheduleMapper.insert(schedule);
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/teacher/courses?error=add_failed";
        }
        return "redirect:/teacher/courses";
    }
    
    /**
     * 编辑课程
     */
    @PostMapping("/courses/edit")
    public String editCourse(Course course, 
                           @RequestParam(value = "weekdays[]", required = false) int[] weekdays,
                           @RequestParam(value = "periods[]", required = false) int[] periods,
                           @RequestParam(value = "classrooms[]", required = false) String[] classrooms,
                           HttpSession session) {
        try {
            // 获取当前登录的老师信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null || currentUser.getRole() != 2) {
                return "redirect:/user/login";
            }
            
            // 通过用户ID获取教师信息
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                return "redirect:/teacher/courses?error=teacher_not_found";
            }
            
            // 确保只能编辑自己的课程
            Course existingCourse = courseService.findById(course.getId());
            if (existingCourse == null || 
                !existingCourse.getTeacher().getId().equals(currentTeacher.getId())) {
                return "redirect:/teacher/courses?error=unauthorized";
            }
            
            // 保持原有的老师信息
            course.setTeacher(currentTeacher);
            
            // 更新课程基本信息
            courseService.update(course);
            
            // 删除旧的时间安排
            courseScheduleMapper.deleteByCourseId(course.getId());
            
            // 添加新的时间安排
            if (weekdays != null && periods != null && classrooms != null) {
                int minLength = Math.min(Math.min(weekdays.length, periods.length), classrooms.length);
                
                for (int i = 0; i < minLength; i++) {
                    // 跳过空的时间安排
                    if (weekdays[i] == 0 || periods[i] == 0) {
                        continue;
                    }
                    
                    CourseSchedule schedule = new CourseSchedule();
                    schedule.setCourse(course);
                    schedule.setWeekday(weekdays[i]);
                    schedule.setPeriod(periods[i]);
                    schedule.setClassroom(classrooms[i] != null && !classrooms[i].trim().isEmpty() ? classrooms[i].trim() : null);
                    
                    // 保存时间安排
                    courseScheduleMapper.insert(schedule);
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/teacher/courses?error=edit_failed";
        }
        return "redirect:/teacher/courses";
    }
    
    /**
     * 删除课程
     */
    @GetMapping("/courses/delete/{id}")
    public String deleteCourse(@PathVariable Long id, HttpSession session) {
        try {
            // 获取当前登录的老师信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null || currentUser.getRole() != 2) {
                return "redirect:/user/login";
            }
            
            // 通过用户ID获取教师信息
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                return "redirect:/teacher/courses?error=teacher_not_found";
            }
            
            // 确保只能删除自己的课程
            Course existingCourse = courseService.findById(id);
            if (existingCourse == null || 
                !existingCourse.getTeacher().getId().equals(currentTeacher.getId())) {
                return "redirect:/teacher/courses?error=unauthorized";
            }
            
            courseService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/teacher/courses";
    }
    
    /**
     * 获取单个课程信息（用于查看和编辑模态框填充）
     */
    @GetMapping("/courses/view/{id}")
    @ResponseBody
    public Map<String, Object> viewCourse(@PathVariable Long id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的老师信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null || currentUser.getRole() != 2) {
                result.put("success", false);
                result.put("message", "用户未登录或权限不足");
                return result;
            }
            
            // 通过用户ID获取教师信息
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                result.put("success", false);
                result.put("message", "无法获取教师信息");
                return result;
            }
            
            Course course = courseService.findById(id);
            if (course != null) {
                // 确保只能查看自己的课程
                if (course.getTeacher().getId().equals(currentTeacher.getId())) {
                    result.put("success", true);
                    result.put("course", course);
                } else {
                    result.put("success", false);
                    result.put("message", "无权限查看此课程");
                }
            } else {
                result.put("success", false);
                result.put("message", "课程不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取课程信息失败：" + e.getMessage());
        }
        return result;
    }

    @GetMapping("/courses/students/{courseId}")
    public String listCourseStudents(@PathVariable Long courseId,
                                    @RequestParam(defaultValue = "1") int page,
                                    @RequestParam(defaultValue = "5") int size,
                                    Model model) {
        try {
            // 获取课程信息
            Course course = courseService.findById(courseId);
            if (course == null) {
                return "redirect:/teacher/courses?error=course_not_found";
            }

            // 获取课程选课学生
            PageInfo<CourseSelection> pageInfo = courseSelectionService.findByCourseIdWithPage(courseId.intValue(), page, size);

            model.addAttribute("course", course);
            model.addAttribute("students", pageInfo.getList());
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", pageInfo.getPages());
            model.addAttribute("totalRecords", pageInfo.getTotal());

            return "teacher/course_students";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/teacher/courses?error=list_students_failed";
        }
    }

    /**
     * 我的选课学生页面 - 显示当前登录老师的所有课程的选课学生
     */
    @GetMapping("/course-students")
    public String listMyCourseStudents(@RequestParam(defaultValue = "1") int page,
                                      @RequestParam(defaultValue = "5") int size,
                                      Model model,
                                      @RequestParam(required = false) Long courseId,
                                      @RequestParam(required = false) Integer statusSearch,
                                      @RequestParam(required = false) String studentSearch,
                                      HttpSession session) {
        
        // 获取当前登录的老师信息
        User currentUser = (User) session.getAttribute("loggedInUser");
        if (currentUser == null) {
            return "redirect:/user/login";
        }
        
        // 通过用户ID获取教师信息
        Teacher currentTeacher = null;
        if (currentUser.getRole() == 2) { // 老师角色
            try {
                currentTeacher = teacherService.findByUserId(currentUser.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if (currentTeacher == null) {
            model.addAttribute("courseSelections", new ArrayList<>());
            model.addAttribute("teacherCourses", new ArrayList<>());
            model.addAttribute("error", "无法获取教师信息，请联系管理员");
            return "teacher/course_students";
        }
        
        try {

            Course teacherCourse = new Course();
            teacherCourse.setTeacher(currentTeacher);
            List<Course> teacherCourses = courseService.findByCondition(teacherCourse);

            List<CourseSelection> allSelections = new ArrayList<>();
            if (teacherCourses != null && !teacherCourses.isEmpty()) {
                for (Course course : teacherCourses) {
                    if (courseId != null && !course.getId().equals(courseId)) {
                        continue;
                    }
                    
                    List<CourseSelection> selections = courseSelectionService.findByCourseId(course.getId());
                    if (selections != null) {
                        for (CourseSelection selection : selections) {

                            if (statusSearch != null && !selection.getStatus().equals(statusSearch)) {
                                continue;
                            }
                            

                            if (studentSearch != null && !studentSearch.trim().isEmpty()) {
                                if (selection.getStudent() != null && 
                                    selection.getStudent().getUser() != null && 
                                    selection.getStudent().getUser().getRealName() != null) {
                                    if (!selection.getStudent().getUser().getRealName().contains(studentSearch.trim())) {
                                        continue;
                                    }
                                } else {
                                    continue;
                                }
                            }
                            
                            allSelections.add(selection);
                        }
                    }
                }
            }
            
            // 手动分页处理
            int start = (page - 1) * size;
            int end = Math.min(start + size, allSelections.size());
            List<CourseSelection> pageSelections = new ArrayList<>();
            if (start < allSelections.size()) {
                pageSelections = allSelections.subList(start, end);
            }
            
            int totalPages = (int) Math.ceil((double) allSelections.size() / size);
            
            // 添加数据到模型
            model.addAttribute("courseSelections", pageSelections);
            model.addAttribute("teacherCourses", teacherCourses);
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", totalPages);
            model.addAttribute("totalRecords", allSelections.size());
            model.addAttribute("searchCourseId", courseId);
            model.addAttribute("statusSearch", statusSearch);
            model.addAttribute("studentSearch", studentSearch);
            model.addAttribute("currentTeacher", currentTeacher);
            
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("courseSelections", new ArrayList<>());
            model.addAttribute("teacherCourses", new ArrayList<>());
            model.addAttribute("error", "获取选课信息失败：" + e.getMessage());
        }

        return "teacher/course_students";
    }

    /**
     * 确认学生选课申请
     */
    @GetMapping("/course-students/confirm/{selectionId}")
    public String confirmCourseSelection(@PathVariable Integer selectionId, HttpSession session) {
        // 获取当前登录的老师信息
        User currentUser = (User) session.getAttribute("loggedInUser");
        if (currentUser == null) {
            return "redirect:/user/login";
        }
        
        try {

            CourseSelection selection = courseSelectionService.findById(selectionId);
            if (selection == null) {
                return "redirect:/teacher/course-students?error=selection_not_found";
            }
            
            // 验证这个选课记录是否属于当前教师的课程
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null || !selection.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                return "redirect:/teacher/course-students?error=access_denied";
            }
            
            // 更新选课状态为已通过
            courseSelectionService.updateStatus(selectionId.longValue(), 1, java.time.LocalDateTime.now().toString());
            
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/teacher/course-students?error=" + e.getMessage();
        }
        
        return "redirect:/teacher/course-students";
    }
    
    /**
     * 拒绝学生选课申请
     */
    @GetMapping("/course-students/cancel/{selectionId}")
    public String cancelCourseSelection(@PathVariable Integer selectionId, HttpSession session) {
        // 获取当前登录的老师信息
        User currentUser = (User) session.getAttribute("loggedInUser");
        if (currentUser == null) {
            return "redirect:/user/login";
        }
        
        try {
            // 获取选课记录
            CourseSelection selection = courseSelectionService.findById(selectionId);
            if (selection == null) {
                return "redirect:/teacher/course-students?error=selection_not_found";
            }
            
            // 验证这个选课记录是否属于当前教师的课程
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null || !selection.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                return "redirect:/teacher/course-students?error=access_denied";
            }
            
            // 更新选课状态为已拒绝
            courseSelectionService.updateStatus(selectionId.longValue(), 2, java.time.LocalDateTime.now().toString());
            
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/teacher/course-students?error=" + e.getMessage();
        }
        
        return "redirect:/teacher/course-students";
    }

    /**
     * 成绩管理页面 - 显示当前登录老师课程的成绩
     */
    @GetMapping("/grades")
    public String listMyGrades(@RequestParam(defaultValue = "1") int page,
                              @RequestParam(defaultValue = "5") int size,
                              Model model,
                              @RequestParam(required = false) Long courseId,
                              @RequestParam(required = false) String studentSearch,
                              HttpSession session) {
        

        
        // 获取当前登录的老师信息
        User currentUser = (User) session.getAttribute("loggedInUser");
        if (currentUser == null) {
            return "redirect:/user/login";
        }
        
        Teacher currentTeacher = null;
        if (currentUser.getRole() == 2) {
            try {
                currentTeacher = teacherService.findByUserId(currentUser.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if (currentTeacher == null) {
            model.addAttribute("grades", new ArrayList<>());
            model.addAttribute("teacherCourses", new ArrayList<>());
            model.addAttribute("error", "无法获取教师信息，请联系管理员");
            return "teacher/grades";
        }
        
        final Teacher finalCurrentTeacher = currentTeacher;
        
        // 获取当前老师的所有课程
        Course teacherCourse = new Course();
        teacherCourse.setTeacher(finalCurrentTeacher);
        List<Course> teacherCourses = courseService.findByCondition(teacherCourse);
        PageInfo<Grade> pageInfo = new PageInfo<>();
        try {
            pageInfo = gradeService.getGradesByTeacherWithPage(finalCurrentTeacher.getId(), courseId, studentSearch, page, size);
        } catch (Exception e) {
            e.printStackTrace();
            pageInfo = new PageInfo<>();
        }
        
        model.addAttribute("grades", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
        model.addAttribute("teacherCourses", teacherCourses != null ? teacherCourses : new ArrayList<>());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchCourseId", courseId);
        model.addAttribute("studentSearch", studentSearch);
        
        return "teacher/grades";
    }

    /**
     * 更新成绩（用于编辑现有成绩）
     */
    @PostMapping("/grades/update")
    @ResponseBody
    public Map<String, Object> updateGrade(@RequestParam Long id,
                                          @RequestParam(required = false) Double regularScore,
                                          @RequestParam(required = false) Double examScore,
                                          HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证权限
            Grade existingGrade = gradeService.findById(id);
            if (existingGrade == null) {
                response.put("success", false);
                response.put("message", "成绩记录不存在");
                return response;
            }
            
            User currentUser = (User) session.getAttribute("loggedInUser");
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            
            if (!existingGrade.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                response.put("success", false);
                response.put("message", "您没有权限修改该课程成绩");
                return response;
            }
            
            // 更新成绩
            existingGrade.setRegularScore(regularScore);
            existingGrade.setExamScore(examScore);
            
            boolean success = gradeService.update(existingGrade);
            if (success) {
                response.put("success", true);
                response.put("message", "成绩更新成功");
            } else {
                response.put("success", false);
                response.put("message", "成绩更新失败");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "成绩更新失败：" + e.getMessage());
        }
        return response;
    }

    /**
     * 添加成绩
     */
    @PostMapping("/grades/add")
    @ResponseBody
    public Map<String, Object> addGrade(HttpServletRequest request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String studentIdStr = request.getParameter("studentId");
            String courseIdStr = request.getParameter("courseId");
            String regularScoreStr = request.getParameter("regularScore");
            String examScoreStr = request.getParameter("examScore");
            
            // 如果getParameter获取不到，尝试从请求体读取
            if (studentIdStr == null && courseIdStr == null && regularScoreStr == null && examScoreStr == null) {
                try {
                    java.io.BufferedReader reader = request.getReader();
                    String line;
                    StringBuilder requestBody = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        requestBody.append(line);
                    }
                    
                    // 如果是application/x-www-form-urlencoded格式，手动解析
                    String bodyContent = requestBody.toString();
                    if (bodyContent.contains("studentId=") && bodyContent.contains("courseId=")) {
                        String[] pairs = bodyContent.split("&");
                        for (String pair : pairs) {
                            String[] keyValue = pair.split("=");
                            if (keyValue.length == 2) {
                                String key = java.net.URLDecoder.decode(keyValue[0], "UTF-8");
                                String value = java.net.URLDecoder.decode(keyValue[1], "UTF-8");
                                switch (key) {
                                    case "studentId":
                                        studentIdStr = value;
                                        break;
                                    case "courseId":
                                        courseIdStr = value;
                                        break;
                                    case "regularScore":
                                        regularScoreStr = value;
                                        break;
                                    case "examScore":
                                        examScoreStr = value;
                                        break;
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            
            // 验证和转换参数
            Long studentId = null;
            Long courseId = null;
            Double regularScore = null;
            Double examScore = null;
            

            if (studentIdStr == null || studentIdStr.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "学生ID不能为空");
                return response;
            }
            try {
                studentId = Long.parseLong(studentIdStr.trim());
            } catch (NumberFormatException e) {
                response.put("success", false);
                response.put("message", "学生ID格式不正确");
                return response;
            }

            if (courseIdStr == null || courseIdStr.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "课程ID不能为空");
                return response;
            }
            try {
                courseId = Long.parseLong(courseIdStr.trim());
            } catch (NumberFormatException e) {
                response.put("success", false);
                response.put("message", "课程ID格式不正确");
                return response;
            }
            

            if (regularScoreStr != null && !regularScoreStr.trim().isEmpty()) {
                try {
                    regularScore = Double.parseDouble(regularScoreStr.trim());
                    if (regularScore < 0 || regularScore > 100) {
                        response.put("success", false);
                        response.put("message", "平时分必须在0-100之间");
                        return response;
                    }
                } catch (NumberFormatException e) {
                    response.put("success", false);
                    response.put("message", "平时分格式不正确");
                    return response;
                }
            }
            

            if (examScoreStr != null && !examScoreStr.trim().isEmpty()) {
                try {
                    examScore = Double.parseDouble(examScoreStr.trim());
                    if (examScore < 0 || examScore > 100) {
                        response.put("success", false);
                        response.put("message", "考试分必须在0-100之间");
                        return response;
                    }
                } catch (NumberFormatException e) {
                    response.put("success", false);
                    response.put("message", "考试分格式不正确");
                    return response;
                }
            }
            

            if (regularScore == null && examScore == null) {
                response.put("success", false);
                response.put("message", "请至少输入平时分或考试分");
                return response;
            }
            

            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return response;
            }
            
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                response.put("success", false);
                response.put("message", "获取教师信息失败");
                return response;
            }
            
            Course course = courseService.findById(courseId);
            if (course == null) {
                response.put("success", false);
                response.put("message", "课程不存在");
                return response;
            }
            
            if (!course.getTeacher().getId().equals(currentTeacher.getId())) {
                response.put("success", false);
                response.put("message", "您没有权限为该课程添加成绩");
                return response;
            }
            

            // 检查是否已存在成绩记录
            Grade existingGrade = new Grade();
            Student searchStudent = new Student();
            searchStudent.setId(studentId);
            existingGrade.setStudent(searchStudent);
            existingGrade.setCourse(course);
            
            List<Grade> existingGrades = gradeService.findByCondition(existingGrade);
            if (existingGrades != null && !existingGrades.isEmpty()) {
                response.put("success", false);
                response.put("message", "该学生该课程已存在成绩记录");
                return response;
            }
            
            // 创建新成绩记录
            Grade grade = new Grade();
            Student student = new Student();
            student.setId(studentId);
            grade.setStudent(student);
            grade.setCourse(course);
            grade.setRegularScore(regularScore);
            grade.setExamScore(examScore);
            
            boolean success = gradeService.add(grade);
            
            if (success) {
                response.put("success", true);
                response.put("message", "成绩添加成功");
            } else {
                response.put("success", false);
                response.put("message", "成绩添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "成绩添加失败：" + e.getMessage());
        }
        
        return response;
    }

    /**
     * 更新平时分
     */
    @PostMapping("/grades/updateRegular")
    @ResponseBody
    public Map<String, Object> updateRegularScore(@RequestParam Long id,
                                                  @RequestParam Double regularScore,
                                                  HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证权限
            Grade existingGrade = gradeService.findById(id);
            if (existingGrade == null) {
                response.put("success", false);
                response.put("message", "成绩记录不存在");
                return response;
            }
            
            User currentUser = (User) session.getAttribute("loggedInUser");
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            
            if (!existingGrade.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                response.put("success", false);
                response.put("message", "您没有权限修改该课程成绩");
                return response;
            }
            
            boolean success = gradeService.updateRegularScore(id.intValue(), regularScore);
            if (success) {
                response.put("success", true);
                response.put("message", "平时分更新成功");
            } else {
                response.put("success", false);
                response.put("message", "平时分更新失败");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "平时分更新失败：" + e.getMessage());
        }
        return response;
    }

    /**
     * 更新考试分
     */
    @PostMapping("/grades/updateExam")
    @ResponseBody
    public Map<String, Object> updateExamScore(@RequestParam Long id,
                                              @RequestParam Double examScore,
                                              HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证权限
            Grade existingGrade = gradeService.findById(id);
            if (existingGrade == null) {
                response.put("success", false);
                response.put("message", "成绩记录不存在");
                return response;
            }
            
            User currentUser = (User) session.getAttribute("loggedInUser");
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            
            if (!existingGrade.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                response.put("success", false);
                response.put("message", "您没有权限修改该课程成绩");
                return response;
            }
            
            boolean success = gradeService.updateExamScore(id.intValue(), examScore);
            if (success) {
                response.put("success", true);
                response.put("message", "考试分更新成功");
            } else {
                response.put("success", false);
                response.put("message", "考试分更新失败");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "考试分更新失败：" + e.getMessage());
        }
        return response;
    }

    /**
     * 获取成绩详情（用于编辑）
     */
    @GetMapping("/grades/view/{id}")
    @ResponseBody
    public Map<String, Object> viewGrade(@PathVariable Long id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证权限
            Grade grade = gradeService.findById(id);
            if (grade == null) {
                response.put("success", false);
                response.put("message", "成绩记录不存在");
                return response;
            }
            
            User currentUser = (User) session.getAttribute("loggedInUser");
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            
            if (!grade.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                response.put("success", false);
                response.put("message", "您没有权限查看该成绩记录");
                return response;
            }
            
            response.put("success", true);
            response.put("grade", grade);
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "获取成绩详情失败：" + e.getMessage());
        }
        return response;
    }

    /**
     * 删除成绩
     */
    @GetMapping("/grades/delete/{id}")
    public String deleteGrade(@PathVariable Long id, HttpSession session) {
        try {
            // 验证权限
            Grade existingGrade = gradeService.findById(id);
            if (existingGrade != null) {
                User currentUser = (User) session.getAttribute("loggedInUser");
                Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
                
                if (existingGrade.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                    gradeService.delete(id.intValue());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/teacher/grades";
    }

    /**
     * 获取课程的学生列表（用于添加成绩时选择学生）
     */
    @GetMapping("/grades/courseStudents/{courseId}")
    @ResponseBody
    public Map<String, Object> getCourseStudents(@PathVariable Long courseId, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        try {
            System.out.println("获取课程学生列表 - 课程ID: " + courseId);
            
            // 验证权限
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                System.out.println("用户未登录");
                response.put("success", false);
                response.put("message", "用户未登录");
                return response;
            }
            
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                System.out.println("获取教师信息失败");
                response.put("success", false);
                response.put("message", "获取教师信息失败");
                return response;
            }
            
            Course course = courseService.findById(courseId);
            if (course == null) {
                System.out.println("课程不存在");
                response.put("success", false);
                response.put("message", "课程不存在");
                return response;
            }
            
            if (!course.getTeacher().getId().equals(currentTeacher.getId())) {
                System.out.println("权限不足 - 课程教师ID: " + course.getTeacher().getId() + ", 当前教师ID: " + currentTeacher.getId());
                response.put("success", false);
                response.put("message", "您没有权限查看该课程学生");
                return response;
            }
            
            // 获取选修该课程的学生
            List<CourseSelection> selections = courseSelectionService.findByCourseId(courseId);
            System.out.println("找到 " + (selections != null ? selections.size() : 0) + " 个选课记录");
            
            List<Student> students = new ArrayList<>();
            if (selections != null) {
                for (CourseSelection selection : selections) {
                    if (selection.getStudent() != null) {
                        students.add(selection.getStudent());
                    }
                }
            }
            
            System.out.println("有效学生数量: " + students.size());
            
            // 获取该课程的所有成绩记录
            Grade gradeQuery = new Grade();
            gradeQuery.setCourse(course);
            List<Grade> grades = gradeService.findByCondition(gradeQuery);
            System.out.println("找到 " + (grades != null ? grades.size() : 0) + " 条成绩记录");
            
            response.put("success", true);
            response.put("students", students);
            response.put("grades", grades != null ? grades : new ArrayList<>());
        } catch (Exception e) {
            System.out.println("获取学生列表异常: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "获取学生列表失败：" + e.getMessage());
        }
        return response;
    }

    /**
     * 检查是否为AJAX请求
     */
    private boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("X-Requested-With");
        String accept = request.getHeader("Accept");
        String contentType = request.getHeader("Content-Type");
        String ajax = request.getParameter("ajax");
        
        System.out.println("=== AJAX检测详情 ===");
        System.out.println("X-Requested-With: " + requestedWith);
        System.out.println("Accept: " + accept);
        System.out.println("Content-Type: " + contentType);
        System.out.println("ajax参数: " + ajax);
        
        boolean result = "XMLHttpRequest".equals(requestedWith) ||
               (accept != null && accept.contains("application/json")) ||
               (contentType != null && contentType.contains("application/json")) ||
               "1".equals(ajax);
               
        System.out.println("AJAX检测结果: " + result);
        return result;
    }

    /**
     * AJAX获取成绩数据（专门用于AJAX请求）
     */
    @GetMapping("/grades/ajax")
    @ResponseBody
    public Map<String, Object> getGradesAjax(@RequestParam(required = false) Long courseId,
                                            @RequestParam(required = false) String studentSearch,
                                            @RequestParam(defaultValue = "1") int page,
                                            @RequestParam(defaultValue = "10") int size,
                                            HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            System.out.println("=== AJAX获取成绩数据 ===");
            System.out.println("courseId: " + courseId);
            System.out.println("studentSearch: " + studentSearch);
            System.out.println("page: " + page + ", size: " + size);
            
            // 获取当前登录的老师信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                System.out.println("用户未登录");
                response.put("success", false);
                response.put("message", "用户未登录");
                return response;
            }
            
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                System.out.println("无法获取教师信息");
                response.put("success", false);
                response.put("message", "无法获取教师信息");
                return response;
            }
            
            System.out.println("当前教师ID: " + currentTeacher.getId());
            
            PageInfo<Grade> pageInfo = new PageInfo<>();
            
            if (courseId != null && courseId > 0) {
                // 验证课程是否属于当前教师
                Course course = courseService.findById(courseId);
                if (course == null) {
                    response.put("success", false);
                    response.put("message", "课程不存在");
                    return response;
                }
                
                if (!course.getTeacher().getId().equals(currentTeacher.getId())) {
                    response.put("success", false);
                    response.put("message", "您没有权限查看该课程成绩");
                    return response;
                }
                
                Grade searchGrade = new Grade();
                searchGrade.setCourse(course);
                
                // 根据学生姓名搜索
                if (studentSearch != null && !studentSearch.trim().isEmpty()) {
                    Student student = new Student();
                    User user = new User();
                    user.setRealName(studentSearch.trim());
                    student.setUser(user);
                    searchGrade.setStudent(student);
                }
                
                pageInfo = gradeService.findByConditionPage(searchGrade, page, size);
                System.out.println("查询到成绩数量: " + (pageInfo.getList() != null ? pageInfo.getList().size() : 0));
            }
            
            response.put("success", true);
            response.put("grades", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
            response.put("totalRecords", pageInfo.getTotal());
            response.put("totalPages", pageInfo.getPages());
            response.put("currentPage", page);
            
            System.out.println("=== AJAX获取成绩数据结束 ===");
            
        } catch (Exception e) {
            System.out.println("AJAX获取成绩数据异常: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "获取成绩数据失败：" + e.getMessage());
        }
        
        return response;
    }

    // ==================== 作业管理功能 ====================

    /**
     * 作业管理页面 - 显示当前登录老师课程的作业
     */
    @GetMapping("/homework")
    public String listMyHomework(@RequestParam(defaultValue = "1") int page,
                                @RequestParam(defaultValue = "5") int size,
                                Model model,
                                @RequestParam(required = false) Long courseId,
                                @RequestParam(required = false) String titleSearch,
                                HttpSession session) {
        // 获取当前登录的老师信息
        User currentUser = (User) session.getAttribute("loggedInUser");
        if (currentUser == null) {
            System.out.println("用户未登录，重定向到登录页");
            return "redirect:/user/login";
        }
        
        System.out.println("当前用户: " + currentUser.getUsername() + ", ID: " + currentUser.getId());
        
        Teacher currentTeacher = null;
        if (currentUser.getRole() == 2) { // 老师角色
            try {
                currentTeacher = teacherService.findByUserId(currentUser.getId());
                System.out.println("获取到教师信息: " + (currentTeacher != null ? currentTeacher.getId() : "null"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if (currentTeacher == null) {
            System.out.println("无法获取教师信息");
            model.addAttribute("homework", new ArrayList<>());
            model.addAttribute("error", "无法获取教师信息，请联系管理员");
            return "teacher/homework";
        }
        
        final Teacher finalCurrentTeacher = currentTeacher;
        
        // 获取当前老师的所有课程
        Course teacherCourse = new Course();
        teacherCourse.setTeacher(finalCurrentTeacher);
        List<Course> teacherCourses = courseService.findByCondition(teacherCourse);
        System.out.println("当前教师的课程数量: " + (teacherCourses != null ? teacherCourses.size() : 0));
        
        PageInfo<Homework> pageInfo = new PageInfo<>();
        try {
            Homework searchHomework = new Homework();
            
            // 根据课程筛选
            if (courseId != null && courseId > 0) {
                Course course = courseService.findById(courseId);
                if (course != null && course.getTeacher().getId().equals(finalCurrentTeacher.getId())) {
                    searchHomework.setCourse(course);
                    System.out.println("按课程筛选作业，课程ID: " + courseId);
                }
            }
            
            // 根据标题搜索
            if (titleSearch != null && !titleSearch.trim().isEmpty()) {
                searchHomework.setTitle(titleSearch.trim());
                System.out.println("按标题搜索作业，标题: " + titleSearch.trim());
            }
            
            // 查询作业，但需要过滤只显示当前老师的课程作业
            pageInfo = homeworkService.getHomeworksByConditionWithPage(searchHomework, page, size);
            System.out.println("查询到作业总数: " + (pageInfo != null ? pageInfo.getTotal() : 0));
            System.out.println("当前页作业数: " + (pageInfo != null && pageInfo.getList() != null ? pageInfo.getList().size() : 0));
            
            // 过滤掉不是当前老师课程的作业
            if (pageInfo.getList() != null) {
                List<Homework> filteredHomework = pageInfo.getList().stream()
                    .filter(homework -> {
                        if (homework.getCourse() != null && homework.getCourse().getTeacher() != null) {
                            boolean isMyHomework = homework.getCourse().getTeacher().getId().equals(finalCurrentTeacher.getId());
                            System.out.println("作业: " + homework.getTitle() + ", 课程: " + homework.getCourse().getName() + 
                                             ", 教师ID: " + homework.getCourse().getTeacher().getId() + 
                                             ", 当前教师ID: " + finalCurrentTeacher.getId() + 
                                             ", 是否匹配: " + isMyHomework);
                            return isMyHomework;
                        }
                        System.out.println("作业课程或教师信息为空: " + homework.getTitle());
                        return false;
                    })
                    .collect(java.util.stream.Collectors.toList());
                
                pageInfo.setList(filteredHomework);
                System.out.println("过滤后的作业数: " + filteredHomework.size());

                System.out.println("保持原始分页信息 - 总数: " + pageInfo.getTotal() + ", 页数: " + pageInfo.getPages());
            } else {
                // 如果原始列表为空，确保分页信息正确
                pageInfo.setPages(0);
                pageInfo.setTotal(0);
                pageInfo.setPageNum(1);
                pageInfo.setPageSize(size);
                System.out.println("原始列表为空，重置分页信息");
            }
            
        } catch (Exception e) {
            System.out.println("查询作业时出现异常: " + e.getMessage());
            e.printStackTrace();
            pageInfo = new PageInfo<>();
        }
        
        model.addAttribute("homework", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
        model.addAttribute("teacherCourses", teacherCourses != null ? teacherCourses : new ArrayList<>());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchCourseId", courseId);
        model.addAttribute("titleSearch", titleSearch);
        return "teacher/homework";
    }

    /**
     * 添加作业
     */
    @PostMapping("/homework/add")
    @ResponseBody
    public Map<String, Object> addHomework(@RequestBody HomeworkRequest request, HttpSession session) {
        System.out.println("=== 开始处理作业添加请求 ===");
        
        // 从request对象中获取参数
        String courseIdStr = request.getCourseId();
        String title = request.getTitle();
        String content = request.getContent();
        String deadline = request.getDeadline();
        
        System.out.println("courseIdStr: " + courseIdStr);
        System.out.println("title: " + title);
        System.out.println("content: " + content);
        System.out.println("deadline: " + deadline);
        
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证参数
            if (courseIdStr == null || courseIdStr.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择课程");
                return response;
            }
            
            if (title == null || title.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "请输入作业标题");
                return response;
            }
            
            if (content == null || content.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "请输入作业内容");
                return response;
            }
            
            if (deadline == null || deadline.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择截止时间");
                return response;
            }
            
            Long courseId;
            try {
                courseId = Long.parseLong(courseIdStr);
            } catch (NumberFormatException e) {
                response.put("success", false);
                response.put("message", "课程ID格式错误");
                return response;
            }
            
            // 验证权限
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                System.out.println("用户未登录");
                response.put("success", false);
                response.put("message", "用户未登录");
                return response;
            }
            
            System.out.println("当前用户: " + currentUser.getUsername());
            
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                response.put("success", false);
                response.put("message", "获取教师信息失败");
                return response;
            }
            
            Course course = courseService.findById(courseId);
            if (course == null) {
                response.put("success", false);
                response.put("message", "课程不存在");
                return response;
            }
            
            if (!course.getTeacher().getId().equals(currentTeacher.getId())) {
                response.put("success", false);
                response.put("message", "您没有权限为该课程添加作业");
                return response;
            }
            
            // 创建作业
            Homework homework = new Homework();
            homework.setCourse(course);
            homework.setTitle(title.trim());
            homework.setContent(content.trim());
            
            // 转换时间格式：从 "yyyy-MM-ddTHH:mm" 转换为 LocalDateTime
            try {
                LocalDateTime deadlineDateTime = LocalDateTime.parse(deadline, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm"));
                homework.setDeadline(deadlineDateTime);
            } catch (Exception e) {
                response.put("success", false);
                response.put("message", "时间格式错误：" + e.getMessage());
                return response;
            }
            
            boolean success = homeworkService.addHomework(homework);
            if (success) {
                response.put("success", true);
                response.put("message", "作业添加成功");
            } else {
                response.put("success", false);
                response.put("message", "作业添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "作业添加失败：" + e.getMessage());
        }
        return response;
    }

    /**
     * 更新作业
     */
    @PostMapping("/homework/update")
    @ResponseBody
    public Map<String, Object> updateHomework(@RequestBody HomeworkUpdateRequest request, HttpSession session) {
        System.out.println("=== 开始处理作业更新请求 ===");
        
        // 从request对象中获取参数
        String idStr = request.getId();
        String title = request.getTitle();
        String content = request.getContent();
        String deadline = request.getDeadline();
        
        System.out.println("idStr: " + idStr);
        System.out.println("title: " + title);
        System.out.println("content: " + content);
        System.out.println("deadline: " + deadline);
        
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证参数
            if (idStr == null || idStr.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "作业ID不能为空");
                return response;
            }
            
            if (title == null || title.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "请输入作业标题");
                return response;
            }
            
            if (content == null || content.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "请输入作业内容");
                return response;
            }
            
            if (deadline == null || deadline.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择截止时间");
                return response;
            }
            
            Long id;
            try {
                id = Long.parseLong(idStr);
            } catch (NumberFormatException e) {
                response.put("success", false);
                response.put("message", "作业ID格式错误");
                return response;
            }
            
            // 验证权限
            Homework existingHomework = homeworkService.getHomeworkById(id);
            if (existingHomework == null) {
                response.put("success", false);
                response.put("message", "作业不存在");
                return response;
            }
            
            User currentUser = (User) session.getAttribute("loggedInUser");
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            
            if (!existingHomework.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                response.put("success", false);
                response.put("message", "您没有权限修改该作业");
                return response;
            }
            
            // 更新作业
            existingHomework.setTitle(title.trim());
            existingHomework.setContent(content.trim());
            
            // 转换时间格式：从 "yyyy-MM-ddTHH:mm" 转换为 LocalDateTime
            try {
                LocalDateTime deadlineDateTime = LocalDateTime.parse(deadline, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm"));
                existingHomework.setDeadline(deadlineDateTime);
            } catch (Exception e) {
                response.put("success", false);
                response.put("message", "时间格式错误：" + e.getMessage());
                return response;
            }
            
            boolean success = homeworkService.updateHomework(existingHomework);
            if (success) {
                response.put("success", true);
                response.put("message", "作业更新成功");
            } else {
                response.put("success", false);
                response.put("message", "作业更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "作业更新失败：" + e.getMessage());
        }
        return response;
    }

    /**
     * 删除作业
     */
    @GetMapping("/homework/delete/{id}")
    public String deleteHomework(@PathVariable Long id, HttpSession session) {
        try {
            // 验证权限
            Homework existingHomework = homeworkService.getHomeworkById(id);
            if (existingHomework != null) {
                User currentUser = (User) session.getAttribute("loggedInUser");
                Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
                
                if (existingHomework.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                    homeworkService.deleteHomework(id);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/teacher/homework";
    }

    /**
     * 获取单个作业信息（用于编辑模态框填充）
     */
    @GetMapping("/homework/view/{id}")
    @ResponseBody
    public Map<String, Object> viewHomework(@PathVariable Long id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的老师信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null || currentUser.getRole() != 2) {
                result.put("success", false);
                result.put("message", "用户未登录或权限不足");
                return result;
            }
            
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                result.put("success", false);
                result.put("message", "无法获取教师信息");
                return result;
            }
            
            Homework homework = homeworkService.getHomeworkById(id);
            if (homework != null) {
                // 确保只能查看自己的课程作业
                if (homework.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                    result.put("success", true);
                    
                    // 创建作业信息Map，避免LocalDateTime序列化问题
                    Map<String, Object> homeworkData = new HashMap<>();
                    homeworkData.put("id", homework.getId());
                    homeworkData.put("title", homework.getTitle());
                    homeworkData.put("content", homework.getContent());
                    homeworkData.put("deadlineStr", homework.getDeadlineStr());
                    if (homework.getCourse() != null) {
                        homeworkData.put("courseName", homework.getCourse().getName());
                    }
                    
                    result.put("homework", homeworkData);
                } else {
                    result.put("success", false);
                    result.put("message", "无权限查看此作业");
                }
            } else {
                result.put("success", false);
                result.put("message", "作业不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取作业信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 查看作业提交情况
     */
    @GetMapping("/homework/submissions/{homeworkId}")
    public String viewHomeworkSubmissions(@PathVariable Long homeworkId,
                                         @RequestParam(defaultValue = "1") int page,
                                         @RequestParam(defaultValue = "5") int size,
                                         Model model,
                                         HttpSession session) {
        try {
            // 验证权限
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                return "redirect:/user/login";
            }
            
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                return "redirect:/teacher/homework?error=teacher_not_found";
            }
            
            Homework homework = homeworkService.getHomeworkById(homeworkId);
            if (homework == null) {
                return "redirect:/teacher/homework?error=homework_not_found";
            }
            
            if (!homework.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                return "redirect:/teacher/homework?error=unauthorized";
            }
            
            // 获取作业提交记录
            List<HomeworkSubmission> submissions = homeworkSubmissionService.getHomeworkSubmissionsByHomeworkId(homeworkId);
            

            int start = (page - 1) * size;
            int end = Math.min(start + size, submissions.size());
            List<HomeworkSubmission> pageSubmissions = submissions.subList(start, end);
            
            int totalPages = (int) Math.ceil((double) submissions.size() / size);
            
            model.addAttribute("homework", homework);
            model.addAttribute("submissions", pageSubmissions);
            model.addAttribute("currentPage", page);
            model.addAttribute("pageSize", size);
            model.addAttribute("totalPages", totalPages);
            model.addAttribute("totalRecords", submissions.size());
            
            return "teacher/homework_submissions";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/teacher/homework?error=view_submissions_failed";
        }
    }

    /**
     * 评分作业提交
     */
    @PostMapping("/homework/grade-main")
    @ResponseBody
    public Map<String, Object> gradeHomeworkSubmissionNew(@RequestParam Long submissionId,
                                                       @RequestParam Double score,
                                                       HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证权限
            HomeworkSubmission submission = homeworkSubmissionService.getHomeworkSubmissionById(submissionId);
            if (submission == null) {
                response.put("success", false);
                response.put("message", "作业提交记录不存在");
                return response;
            }
            
            User currentUser = (User) session.getAttribute("loggedInUser");
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            
            if (!submission.getHomework().getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                response.put("success", false);
                response.put("message", "您没有权限评分该作业");
                return response;
            }
            
            boolean success = homeworkSubmissionService.gradeHomeworkSubmission(submissionId, score);
            if (success) {
                response.put("success", true);
                response.put("message", "评分成功");
            } else {
                response.put("success", false);
                response.put("message", "评分失败");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "评分失败：" + e.getMessage());
        }
        return response;
    }



    /**
     * 考勤管理页面 - 显示当前登录老师课程的考勤情况
     */
    @GetMapping("/attendance")
    public String listMyAttendance(@RequestParam(defaultValue = "1") int page,
                                  @RequestParam(defaultValue = "10") int size,
                                  Model model,
                                  @RequestParam(required = false) Long courseId,
                                  @RequestParam(required = false) String dateSearch,
                                  @RequestParam(required = false) Integer statusSearch,
                                  HttpSession session) {
        
        System.out.println("=== 考勤管理页面请求开始 ===");
        
        // 获取当前登录的老师信息
        User currentUser = (User) session.getAttribute("loggedInUser");
        if (currentUser == null) {
            System.out.println("用户未登录，重定向到登录页");
            return "redirect:/user/login";
        }
        
        System.out.println("当前用户: " + currentUser.getUsername() + ", ID: " + currentUser.getId());
        
        Teacher currentTeacher = null;
        if (currentUser.getRole() == 2) { // 老师角色
            try {
                currentTeacher = teacherService.findByUserId(currentUser.getId());
                System.out.println("获取到教师信息: " + (currentTeacher != null ? currentTeacher.getId() : "null"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if (currentTeacher == null) {
            System.out.println("无法获取教师信息");
            model.addAttribute("attendances", new ArrayList<>());
            model.addAttribute("error", "无法获取教师信息，请联系管理员");
            return "teacher/attendance";
        }
        
        final Teacher finalCurrentTeacher = currentTeacher;
        
        // 获取当前老师的所有课程
        Course teacherCourse = new Course();
        teacherCourse.setTeacher(finalCurrentTeacher);
        List<Course> teacherCourses = courseService.findByCondition(teacherCourse);
        System.out.println("当前教师的课程数量: " + (teacherCourses != null ? teacherCourses.size() : 0));
        
        PageInfo<Attendance> pageInfo = new PageInfo<>();
        try {
            Attendance searchAttendance = new Attendance();
            
            // 根据课程筛选
            if (courseId != null && courseId > 0) {
                Course course = courseService.findById(courseId);
                if (course != null && course.getTeacher().getId().equals(finalCurrentTeacher.getId())) {
                    searchAttendance.setCourse(course);
                    System.out.println("按课程筛选考勤，课程ID: " + courseId);
                }
            }
            
            // 根据日期搜索
            if (dateSearch != null && !dateSearch.trim().isEmpty()) {
                searchAttendance.setDate(dateSearch.trim());
                System.out.println("按日期搜索考勤，日期: " + dateSearch.trim());
            }
            
            // 根据状态搜索
            if (statusSearch != null) {
                searchAttendance.setStatus(statusSearch);
                System.out.println("按状态搜索考勤，状态: " + statusSearch);
            }
            
            // 查询考勤记录
            pageInfo = attendanceService.getAttendancesByConditionWithPage(searchAttendance, page, size);
            System.out.println("查询到考勤总数: " + (pageInfo != null ? pageInfo.getTotal() : 0));
            System.out.println("当前页考勤数: " + (pageInfo != null && pageInfo.getList() != null ? pageInfo.getList().size() : 0));
            

            if (pageInfo.getList() != null) {
                List<Attendance> filteredAttendances = pageInfo.getList().stream()
                    .filter(attendance -> {
                        if (attendance.getCourse() != null && attendance.getCourse().getTeacher() != null) {
                            boolean isMyAttendance = attendance.getCourse().getTeacher().getId().equals(finalCurrentTeacher.getId());
                            return isMyAttendance;
                        }
                        return false;
                    })
                    .collect(java.util.stream.Collectors.toList());
                
                pageInfo.setList(filteredAttendances);
                System.out.println("过滤后的考勤数: " + filteredAttendances.size());
            }
            
        } catch (Exception e) {
            System.out.println("查询考勤时出现异常: " + e.getMessage());
            e.printStackTrace();
            pageInfo = new PageInfo<>();
        }
        
        model.addAttribute("attendances", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
        model.addAttribute("teacherCourses", teacherCourses != null ? teacherCourses : new ArrayList<>());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchCourseId", courseId);
        model.addAttribute("dateSearch", dateSearch);
        model.addAttribute("statusSearch", statusSearch);
        
        System.out.println("=== 考勤管理页面请求结束 ===");
        
        return "teacher/attendance";
    }

    /**
     * 更新考勤状态
     */
    @PostMapping("/attendance/update")
    @ResponseBody
    public Map<String, Object> updateAttendance(@RequestParam Long attendanceId,
                                               @RequestParam Integer status,
                                               HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证权限
            Attendance existingAttendance = attendanceService.getAttendanceById(attendanceId);
            if (existingAttendance == null) {
                response.put("success", false);
                response.put("message", "考勤记录不存在");
                return response;
            }
            
            User currentUser = (User) session.getAttribute("loggedInUser");
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            
            if (!existingAttendance.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                response.put("success", false);
                response.put("message", "您没有权限修改该考勤记录");
                return response;
            }
            
            // 更新考勤状态
            existingAttendance.setStatus(status);
            boolean success = attendanceService.updateAttendance(existingAttendance);
            
            if (success) {
                response.put("success", true);
                response.put("message", "考勤状态更新成功");
            } else {
                response.put("success", false);
                response.put("message", "考勤状态更新失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "考勤状态更新失败：" + e.getMessage());
        }
        
        return response;
    }

    /**
     * 获取课程学生列表（用于考勤录入）
     */
    @GetMapping("/attendance/courseStudents/{courseId}")
    @ResponseBody
    public Map<String, Object> getCourseStudentsForAttendance(@PathVariable Long courseId, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        try {
            System.out.println("获取课程学生列表用于考勤 - 课程ID: " + courseId);
            
            // 验证权限
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return response;
            }
            
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                response.put("success", false);
                response.put("message", "获取教师信息失败");
                return response;
            }
            
            Course course = courseService.findById(courseId);
            if (course == null) {
                response.put("success", false);
                response.put("message", "课程不存在");
                return response;
            }
            
            if (!course.getTeacher().getId().equals(currentTeacher.getId())) {
                response.put("success", false);
                response.put("message", "您没有权限查看该课程学生");
                return response;
            }
            
            // 获取选修该课程的学生
            List<CourseSelection> selections = courseSelectionService.findByCourseId(courseId);
            System.out.println("找到 " + (selections != null ? selections.size() : 0) + " 个选课记录");
            
            List<Student> students = new ArrayList<>();
            if (selections != null) {
                for (CourseSelection selection : selections) {
                    if (selection.getStudent() != null) {
                        students.add(selection.getStudent());
                    }
                }
            }
            
            System.out.println("有效学生数量: " + students.size());
            
            // 获取该课程的所有成绩记录
            Grade gradeQuery = new Grade();
            gradeQuery.setCourse(course);
            List<Grade> grades = gradeService.findByCondition(gradeQuery);
            System.out.println("找到 " + (grades != null ? grades.size() : 0) + " 条成绩记录");
            
            response.put("success", true);
            response.put("students", students);
            response.put("grades", grades != null ? grades : new ArrayList<>());
        } catch (Exception e) {
            System.out.println("获取学生列表异常: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "获取学生列表失败：" + e.getMessage());
        }
        return response;
    }

    /**
     * 考勤统计页面
     */
    @GetMapping("/attendance/statistics")
    public String attendanceStatistics(@RequestParam(required = false) Long courseId,
                                      @RequestParam(required = false) String startDate,
                                      @RequestParam(required = false) String endDate,
                                      Model model,
                                      HttpSession session) {
        
        System.out.println("=== 考勤统计页面请求开始 ===");
        
        // 获取当前登录的老师信息
        User currentUser = (User) session.getAttribute("loggedInUser");
        if (currentUser == null) {
            return "redirect:/user/login";
        }
        
        Teacher currentTeacher = null;
        if (currentUser.getRole() == 2) {
            try {
                currentTeacher = teacherService.findByUserId(currentUser.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if (currentTeacher == null) {
            model.addAttribute("error", "无法获取教师信息，请联系管理员");
            return "teacher/attendance_statistics";
        }
        
        // 获取当前老师的所有课程
        Course teacherCourse = new Course();
        teacherCourse.setTeacher(currentTeacher);
        List<Course> teacherCourses = courseService.findByCondition(teacherCourse);
        

        Map<String, Object> statisticsData = new HashMap<>();
        if (courseId != null && courseId > 0) {
            Course selectedCourse = courseService.findById(courseId);
            if (selectedCourse != null && selectedCourse.getTeacher().getId().equals(currentTeacher.getId())) {

                statisticsData.put("selectedCourse", selectedCourse);

                List<CourseSelection> selections = courseSelectionService.findByCourseId(courseId);
                if (selections != null) {
                    for (CourseSelection selection : selections) {
                        if (selection.getStudent() != null) {
                            Map<String, Integer> studentStats = attendanceService.countAttendanceStatusByStudentIdAndCourseId(
                                selection.getStudent().getId().intValue(), courseId.intValue());
                            // 处理统计数据
                        }
                    }
                }
            }
        }
        
        model.addAttribute("teacherCourses", teacherCourses != null ? teacherCourses : new ArrayList<>());
        model.addAttribute("selectedCourseId", courseId);
        model.addAttribute("startDate", startDate);
        model.addAttribute("endDate", endDate);
        model.addAttribute("statisticsData", statisticsData);
        
        return "teacher/attendance_statistics";
    }


    /**
     * 请假管理页面 - 显示需要审批的请假申请
     */
    @GetMapping("/leave")
    public String listLeaveApplications(@RequestParam(defaultValue = "1") int page,
                                       @RequestParam(defaultValue = "10") int size,
                                       Model model,
                                       @RequestParam(required = false) Long courseId,
                                       @RequestParam(required = false) Integer statusSearch,
                                       HttpSession session) {
        
        System.out.println("=== 请假管理页面请求开始 ===");
        
        // 获取当前登录的老师信息
        User currentUser = (User) session.getAttribute("loggedInUser");
        if (currentUser == null) {
            return "redirect:/user/login";
        }
        
        Teacher currentTeacher = null;
        if (currentUser.getRole() == 2) {
            try {
                currentTeacher = teacherService.findByUserId(currentUser.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if (currentTeacher == null) {
            model.addAttribute("leaves", new ArrayList<>());
            model.addAttribute("error", "无法获取教师信息，请联系管理员");
            return "teacher/leave";
        }
        
        final Teacher finalCurrentTeacher = currentTeacher;
        
        // 获取当前老师的所有课程
        Course teacherCourse = new Course();
        teacherCourse.setTeacher(finalCurrentTeacher);
        List<Course> teacherCourses = courseService.findByCondition(teacherCourse);
        
        PageInfo<Leave> pageInfo = new PageInfo<>();
        try {
            // 直接通过LeaveService查询属于当前教师课程的请假记录
            pageInfo = leaveService.getLeavesByTeacherWithPage(finalCurrentTeacher.getId(), courseId, statusSearch, page, size);
            
        } catch (Exception e) {
            e.printStackTrace();
            pageInfo = new PageInfo<>();
            System.out.println("查询请假记录失败: " + e.getMessage());
        }
        
        System.out.println("=== 请假查询调试信息 ===");
        System.out.println("当前教师ID: " + finalCurrentTeacher.getId());
        System.out.println("查询到的请假记录数量: " + (pageInfo.getList() != null ? pageInfo.getList().size() : 0));
        System.out.println("总记录数: " + pageInfo.getTotal());
        
        model.addAttribute("leaves", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
        model.addAttribute("teacherCourses", teacherCourses != null ? teacherCourses : new ArrayList<>());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchCourseId", courseId);
        model.addAttribute("statusSearch", statusSearch);
        
        return "teacher/leave";
    }

    /**
     * 审批请假申请
     */
    @PostMapping("/leave/approve")
    @ResponseBody
    public Map<String, Object> approveLeave(@RequestParam Integer leaveId,
                                           @RequestParam Integer status,
                                           HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证权限
            Leave existingLeave = leaveService.getLeaveById(leaveId);
            if (existingLeave == null) {
                response.put("success", false);
                response.put("message", "请假记录不存在");
                return response;
            }
            
            User currentUser = (User) session.getAttribute("loggedInUser");
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            
            if (!existingLeave.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                response.put("success", false);
                response.put("message", "您没有权限审批该请假申请");
                return response;
            }
            
            // 审批请假
            boolean success = leaveService.approveLeave(leaveId, status);
            if (success) {
                String statusText = status == 1 ? "通过" : "不通过";
                response.put("success", true);
                response.put("message", "请假申请审批" + statusText + "成功");
            } else {
                response.put("success", false);
                response.put("message", "请假申请审批失败");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "请假申请审批失败：" + e.getMessage());
        }
        
        return response;
    }

    /**
     * 查看请假详情
     */
    @GetMapping("/leave/view/{id}")
    @ResponseBody
    public Map<String, Object> viewLeave(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的老师信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null || currentUser.getRole() != 2) {
                result.put("success", false);
                result.put("message", "用户未登录或权限不足");
                return result;
            }
            
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                result.put("success", false);
                result.put("message", "无法获取教师信息");
                return result;
            }
            
            Leave leave = leaveService.getLeaveById(id);
            if (leave != null) {
                // 确保只能查看自己课程的请假申请
                if (leave.getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                    result.put("success", true);
                    result.put("leave", leave);
                } else {
                    result.put("success", false);
                    result.put("message", "无权限查看此请假申请");
                }
            } else {
                result.put("success", false);
                result.put("message", "请假申请不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取请假信息失败：" + e.getMessage());
        }
        return result;
    }


    /**
     * 教学评价页面 - 显示当前登录老师收到的教学评价
     */
    @GetMapping("/evaluation")
    public String listMyEvaluations(@RequestParam(defaultValue = "1") int page,
                                   @RequestParam(defaultValue = "10") int size,
                                   Model model,
                                   @RequestParam(required = false) Long courseId,
                                   @RequestParam(required = false) Integer scoreSearch,
                                   HttpSession session) {
        
        System.out.println("=== 教学评价页面请求开始 ===");
        
        // 获取当前登录的老师信息
        User currentUser = (User) session.getAttribute("loggedInUser");
        if (currentUser == null) {
            return "redirect:/user/login";
        }
        
        Teacher currentTeacher = null;
        if (currentUser.getRole() == 2) {
            try {
                currentTeacher = teacherService.findByUserId(currentUser.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if (currentTeacher == null) {
            model.addAttribute("evaluations", new ArrayList<>());
            model.addAttribute("error", "无法获取教师信息，请联系管理员");
            return "teacher/evaluation";
        }
        
        final Teacher finalCurrentTeacher = currentTeacher;
        
        // 获取当前老师的所有课程
        Course teacherCourse = new Course();
        teacherCourse.setTeacher(finalCurrentTeacher);
        List<Course> teacherCourses = courseService.findByCondition(teacherCourse);
        
        PageInfo<Evaluation> pageInfo = new PageInfo<>();
        try {
            Evaluation searchEvaluation = new Evaluation();
            searchEvaluation.setTeacher(finalCurrentTeacher);
            
            // 根据课程筛选
            if (courseId != null && courseId > 0) {
                Course course = courseService.findById(courseId);
                if (course != null && course.getTeacher().getId().equals(finalCurrentTeacher.getId())) {
                    searchEvaluation.setCourse(course);
                }
            }
            
            // 根据评分搜索
            if (scoreSearch != null) {
                searchEvaluation.setScore(scoreSearch);
            }
            
            // 查询教学评价
            pageInfo = evaluationService.findEvaluationsByCondition(page, size, searchEvaluation);
            
        } catch (Exception e) {
            e.printStackTrace();
            pageInfo = new PageInfo<>();
        }
        
        model.addAttribute("evaluations", pageInfo.getList() != null ? pageInfo.getList() : new ArrayList<>());
        model.addAttribute("teacherCourses", teacherCourses != null ? teacherCourses : new ArrayList<>());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchCourseId", courseId);
        model.addAttribute("scoreSearch", scoreSearch);
        
        return "teacher/evaluation";
    }

    /**
     * 查看评价详情
     */
    @GetMapping("/evaluation/view/{id}")
    @ResponseBody
    public Map<String, Object> viewEvaluation(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前登录的老师信息
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null || currentUser.getRole() != 2) {
                result.put("success", false);
                result.put("message", "用户未登录或权限不足");
                return result;
            }
            
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                result.put("success", false);
                result.put("message", "无法获取教师信息");
                return result;
            }
            
            Evaluation evaluation = evaluationService.getEvaluationById(id);
            if (evaluation != null) {
                // 确保只能查看自己的教学评价
                if (evaluation.getTeacher().getId().equals(currentTeacher.getId())) {
                    result.put("success", true);
                    result.put("evaluation", evaluation);
                } else {
                    result.put("success", false);
                    result.put("message", "无权限查看此评价");
                }
            } else {
                result.put("success", false);
                result.put("message", "评价不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取评价信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 查看作业提交详情
     */
    @GetMapping("/homework/submission/view/{id}")
    public String viewHomeworkSubmissionDetail(@PathVariable Long id, Model model, HttpSession session) {
        try {
            // 验证权限
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                return "redirect:/user/login";
            }
            
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                return "redirect:/teacher/homework?error=teacher_not_found";
            }
            
            HomeworkSubmission submission = homeworkSubmissionService.getHomeworkSubmissionById(id);
            if (submission == null) {
                return "redirect:/teacher/homework?error=submission_not_found";
            }
            
            if (!submission.getHomework().getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                return "redirect:/teacher/homework?error=unauthorized";
            }
            
            model.addAttribute("submission", submission);
            return "teacher/homework_submission_detail";
            
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/teacher/homework?error=view_submission_failed";
        }
    }

    /**
     * 获取作业提交详情（AJAX）
     */
    @GetMapping("/homework/submission/detail/{id}")
    @ResponseBody
    public Map<String, Object> getHomeworkSubmissionDetail(@PathVariable Long id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 验证权限
            User currentUser = (User) session.getAttribute("loggedInUser");
            if (currentUser == null) {
                System.out.println("用户未登录");
                response.put("success", false);
                response.put("message", "用户未登录");
                return response;
            }
            
            System.out.println("当前用户: " + currentUser.getUsername());
            
            Teacher currentTeacher = teacherService.findByUserId(currentUser.getId());
            if (currentTeacher == null) {
                System.out.println("获取教师信息失败");
                response.put("success", false);
                response.put("message", "获取教师信息失败");
                return response;
            }
            
            HomeworkSubmission submission = homeworkSubmissionService.getHomeworkSubmissionById(id);
            if (submission == null) {
                System.out.println("作业提交记录不存在，ID: " + id);
                response.put("success", false);
                response.put("message", "作业提交记录不存在");
                return response;
            }
            
            if (!submission.getHomework().getCourse().getTeacher().getId().equals(currentTeacher.getId())) {
                System.out.println("权限验证失败");
                response.put("success", false);
                response.put("message", "您没有权限查看该作业提交");
                return response;
            }

            // 构建提交详情数据，避免LocalDateTime序列化问题
            Map<String, Object> submissionData = new HashMap<>();
            submissionData.put("id", submission.getId());
            submissionData.put("content", submission.getContent());
            submissionData.put("fileUrl", submission.getFileUrl());
            submissionData.put("score", submission.getScore());
            submissionData.put("createTimeStr", submission.getCreateTimeStr());
            // 学生信息
            Map<String, Object> studentData = new HashMap<>();
            if (submission.getStudent() != null) {
                studentData.put("id", submission.getStudent().getId());
                
                // 用户信息
                Map<String, Object> userData = new HashMap<>();
                if (submission.getStudent().getUser() != null) {
                    userData.put("username", submission.getStudent().getUser().getUsername());
                    userData.put("realName", submission.getStudent().getUser().getRealName());
                }
                studentData.put("user", userData);
                
                // 班级信息
                Map<String, Object> clazzData = new HashMap<>();
                if (submission.getStudent().getClazz() != null) {
                    clazzData.put("name", submission.getStudent().getClazz().getName());
                }
                studentData.put("clazz", clazzData);
            }
            submissionData.put("student", studentData);
            
            // 作业信息
            Map<String, Object> homeworkData = new HashMap<>();
            if (submission.getHomework() != null) {
                homeworkData.put("id", submission.getHomework().getId());
                homeworkData.put("title", submission.getHomework().getTitle());
                homeworkData.put("content", submission.getHomework().getContent());
                homeworkData.put("deadlineStr", submission.getHomework().getDeadlineStr());
                
                // 课程信息
                Map<String, Object> courseData = new HashMap<>();
                if (submission.getHomework().getCourse() != null) {
                    courseData.put("name", submission.getHomework().getCourse().getName());
                }
                homeworkData.put("course", courseData);
            }
            submissionData.put("homework", homeworkData);
            
            response.put("success", true);
            response.put("submission", submissionData);
            
            System.out.println("响应数据构建完成");
            
        } catch (Exception e) {
            System.out.println("获取作业提交详情异常: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "获取作业提交详情失败：" + e.getMessage());
        }

        return response;
    }
    
    /**
     * 评分作业提交
     */
    @PostMapping("/homework/submission/score")
    @ResponseBody
    public Map<String, Object> scoreHomeworkSubmission(@RequestParam Long submissionId,
                                                       @RequestParam Double score,
                                                       HttpSession session) {

        return gradeHomeworkSubmissionNew(submissionId, score, session);
    }
} 